import os
import sys
import tinify
'''
	列出所有path及其子目录下符合fileter条件的文件
'''
def list_dir(path, res, filter):
	if path:
		for file in os.listdir(path):
			temp_dir = os.path.join(path, file)
			if os.path.isdir(temp_dir):
				list_dir(temp_dir, res, filter)
			else:
				if (file.endswith(filter) and not file.startswith(".")):
					res.append(temp_dir)
		return res
	else:
		return res

'''
	使用find 命令搜索所有path及其子目录下符合fileter条件的文件
'''
def list_dir_by_shell(path, filter):
	find_file_shell = 'find ' + path + ' -type f -name ' + '*' + filter
	# print(find_file_shell)
	output = os.popen(find_file_shell)
	result = output.read()
	# print(result)
	return result.split()

'''
	tiny 压缩
'''
def tiny(path, filter):
	tinify.key = "J3ufeOH47y0x5NJVvdbBJY3DkhI7EzWZ"
	res = []
	list_dir(path, res, filter)
	# res = list_dir_by_shell(path, filter)
	if res:
		tiny_dir_name = "tiny_" + os.path.basename(path) ;
		tiny_dir_path = os.path.join(os.path.dirname(path), tiny_dir_name)
		if not os.path.exists(tiny_dir_path):
			os.makedirs(tiny_dir_path)
		for file in res:
			print("压缩开始" + file)
			source = tinify.from_file(file)
			tiny_file = os.path.join(tiny_dir_path, os.path.basename(file))
			source.to_file(tiny_file)
			print(file + "tiny 压缩成功:压缩后的文件为:" + tiny_file)
	else:
		print("没有要压缩的文件")
	

def main():
	if len(sys.argv) <= 2:
		print("请输入要压缩的目录及过滤条件")
		return 
	path = sys.argv[1]
	filter = sys.argv[2]
	tiny(path, filter)

if __name__ == "__main__":
	main()